#include <fstream>
#include <vector>
#include <iterator>
#include <string>
#include "BinFiles.h"

using namespace std;


bool SaveToFile(const std::string& filename, const vector<char>& bin)
{
	std::ofstream f(filename, std::fstream::binary);

	if (!f.is_open())
	{
		// save to file failed
		return false;
	}

	copy(bin.begin(), bin.end(), ostream_iterator<char>(f));

	return true;
}

bool LoadFromFile(const std::string& filename, vector<char>& bin)
{
	std::fstream f(filename, (std::fstream::in | std::fstream::binary));

	if (!f.is_open())
	{
		// load from file failed
		return false;
	}

	bin = vector<char>((istreambuf_iterator<char>(f)), istreambuf_iterator<char>());

	return true;
}

bool SaveBinaries(const std::vector<vector<char>>& binaries)
{
	bool result;
	char filename[256];

	std::ofstream f("prog.idx");
	if (!f.is_open())
	{
		// load from file failed
		return false;
	}

	f << binaries.size() << std::endl;

	for (decltype(binaries.size()) i = 0; i < binaries.size(); i++)
	{
		sprintf_s(filename, sizeof(filename), "prog%d.bin", (int)i);

		std::string filename = string("prog") + to_string(i) + string(".bin");

		result = SaveToFile(filename, binaries[i]);
		if (!result)
		{
			printf("Save Failed!\n");
			return false;
		}
	}

	return true;
}

bool LoadBinaries(vector<vector<char>>& binaries)
{
	std::ifstream f("prog.idx");
	if (!f.is_open())
	{
		// load from file failed
		return false;
	}

	int num;
	f >> num;

	binaries.resize(num);

	bool result;
	for (size_t i = 0; i < num; i++)
	{
		string filename = string("prog") + to_string(i) + string(".bin");

		result = LoadFromFile(filename, binaries[i]);
		if (!result)
		{
			printf("Load Failed!\n");
			return false;
		}
	}

	return true;
}
